import { useLogin, useRegister } from '@/hooks/login-hooks';
// import { useSystemConfig } from '@/hooks/system-hooks';
import React, { useState } from 'react';
import { Form, Input, Button } from 'antd';
// import { useTranslation } from 'react-i18next';
import { useNavigate } from 'umi';
// import { rsaPsw } from '@/utils';
import useStore from '@/store';

// 直接引用图片资源
import bgImg from '@/assets/img/login/bg1.jpg';
import userImg from '@/assets/img/login/user.png';
import editImg from '@/assets/img/login/edit.png';
import earImg from '@/assets/img/login/ear.png';
import logImg from '@/assets/img/login/log.png';
import log1Img from '@/assets/img/login/log1.png';
import userService from '@/services/user-service';
import i18n from '@/locales/config';
import { LanguageTranslationMap } from '@/constants/common';
import './index.less'


const Login = () => {
  const navigate = useNavigate();
  const { login, loading: signLoading } = useLogin();
  const { loading: registerLoading } = useRegister();
  const loading = signLoading || registerLoading;
  const [form] = Form.useForm();
  const [agreed, setAgreed] = useState(true);
  const [passwordVisible, setPasswordVisible] = useState(false);
  // login 成功之后，调用useFetchUserInfo 完成用户信息获取
  const { setUserInfo, clearUserInfo, clearChatSession } = useStore();

  const onCheck = async () => {
    try {
      const params = await form.validateFields();
      const password = params.password;
      // const rsaPassWord = rsaPsw(password) as string;
      // 由于没有退出按钮，则登录的时候先清空存储的数据
      clearUserInfo();
      clearChatSession();
      const code = await login({
        "auAccount": `${params.phone}`.trim(), // Using phone as email for now
        "auPassword": password,
      });
      // console.log(code)
      
      if (code === 200) {
        // 登录成功清空之前的数据
        // 先获取用户信息
        try {
          // 使用queryClient刷新用户信息
          const { data } = await userService.user_info();
          if (data.retCode === 200) {
            i18n.changeLanguage(
              LanguageTranslationMap[
                data.data.language as keyof typeof LanguageTranslationMap
              ],
            );
          }
          // 存储用户信息到store里面，
          setUserInfo(data?.data?.adminuser ?? {});
          setTimeout(() => {
            navigate('/talk');
          }, 1000)
          // 导航到对话页面
          // navigate('/talk');
          // navigate('/knowledge');
        } catch (error) {
          console.error('获取用户信息失败:', error);
          // 即使获取用户信息失败，也尝试导航
          navigate('/talk');
        }
      }
    } catch (errorInfo) {
      console.log('Failed:', errorInfo);
    }
  };

  const toggleAgreement = () => {
    // 直接切换agreed状态，不依赖于事件对象
    const newAgreedState = !agreed;
    console.log('toggleAgreement', newAgreedState);
    setAgreed(newAgreedState);
  };

  const togglePasswordVisibility = () => {
    setPasswordVisible(!passwordVisible);
  };

  // 使用 Tailwind 类代替内联样式

  return (
    <div className="bg-cover bg-center bg-no-repeat w-full flex flex-col justify-center items-center relative safe-area-container" style={{ backgroundImage: `url(${bgImg})` }}>
      <div className="w-full px-[110px] py-6 flex flex-col items-center">
        <div className="text-center mb-6 md:mb-8 lg:mb-10">
          <div className="mb-[15px]">
            <img src={logImg} alt="Logo" className="w-[180px] mx-auto" loading="lazy" />
          </div>
          <div className="mb-[88px]">
            <img src={log1Img} alt="Title" className="w-[244px]  mx-auto" loading="lazy" />
          </div>
        </div>
        <Form
          form={form}
          layout="vertical"
          name="login_form"
          className="w-full"
        >
          <Form.Item
            name="phone"
            rules={[{ required: true, message: '请输入手机号码' }]}
          >
            <div className="relative w-full">
              <div className="absolute left-4 sm:left-5 md:left-6 top-1/2 transform -translate-y-1/2 z-10">
                <img src={userImg} alt="User" className="w-[24px] h-[24px]" loading="lazy" />
              </div>
              <Input 
                placeholder="请输入手机号码" 
                className="w-full h-[56px]  bg-white border border-[#3F81F3] rounded-[28px] text-[16px] pl-[60px]"
                style={{
                  fontFamily: 'PingFangSC-Regular',
                  fontWeight: 400,
                  color: '#959CAC',
                }}
              />
            </div>
          </Form.Item>
          
          <Form.Item
            name="password"
            rules={[{ required: true, message: '请输入您的密码' }]}
          >
            <div className="relative w-full">
              <div className="absolute left-4 sm:left-5 md:left-6 top-1/2 transform -translate-y-1/2 z-10">
                <img src={editImg} alt="Password" className="w-[24px] h-[24px]" loading="lazy" />
              </div>
              <Input
                type={passwordVisible ? "text" : "password"}
                placeholder="请输入您的密码"
                className="w-full h-[56px] bg-white border border-[#3F81F3] rounded-[28px] text-[16px] pl-[60px] "
                onPressEnter={onCheck}
                style={{
                  fontFamily: 'PingFangSC-Regular',
                  fontWeight: 400,
                  color: '#959CAC',
                }}
              />
              <div 
                className="absolute right-4 sm:right-5 md:right-6 top-1/2 transform -translate-y-1/2 cursor-pointer z-10"
                onClick={togglePasswordVisibility}
              >
                <img src={earImg} alt="Show Password" className="w-[24px] h-[24px]" loading="lazy" />
              </div>
            </div>
          </Form.Item>
          <div className="flex items-center justify-center mt-6 md:mt-8">
            <Button
              type="primary"
              block
              onClick={onCheck}
              loading={loading}
              className="w-full h-[56px] rounded-[28px] text-[18px] bg-[#3F81F3] border-none text-white shadow-md"
              disabled={!agreed}
            >
              登录
            </Button>
          </div>
        </Form>
        
        <div className="fixed bottom-0  left-0 right-0 mx-auto w-full text-center px-4 safe-area-pb1">
          <div className="flex items-center justify-center cursor-pointer" onClick={toggleAgreement}>
            <div 
              className={`w-[12px] h-[12px] flex items-center justify-center rounded-full border transition-all duration-200 ${agreed ? 'bg-[#3F81F3] border-[#3F81F3]' : 'border-[#989898] bg-transparent'}`}
            >
              {agreed && <div className="w-[8px] h-[8px] rounded-full bg-white"></div>}
            </div>
            <span className="text-[12px] text-[#989898] ml-[4px]">
              阅读并同意 <a href="#" className="text-[#3F81F3]">《用户协议》</a> 和 <a href="#" className="text-[#3F81F3]">《隐私政策》</a>
            </span>
          </div>
        </div>
      </div>
    </div>
  );
};

export default Login;